package org.kfive.nova.io.mina.echo;

import org.apache.mina.core.RuntimeIoException;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.prefixedstring.PrefixedStringCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;

/**
 * TODO
 *
 * @author zhanwu.lzw
 * @date 2018年01月25日 15:22
 */
public class EchoClient {

    public static void main(String[] args) throws Exception {
        IoConnector connector = new NioSocketConnector();
        connector.getFilterChain().addLast("logger", new LoggingFilter());
        connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new PrefixedStringCodecFactory(Charset.forName("UTF-8"))));
        connector.setHandler(new EchoClientHandler());
        IoSession session = null;
        for (; ; ) {
            try {
                ConnectFuture future = connector.connect(new InetSocketAddress("127.0.0.1", 9123));
                future.awaitUninterruptibly();
                session = future.getSession();
                System.out.println("连接成功");
                break;
            } catch (RuntimeIoException e) {
                System.err.println("连接失败");
                e.printStackTrace();
                Thread.sleep(5000);
            }
        }

        final BufferedReader inReader = new BufferedReader(new InputStreamReader(System.in));
        do{

            final String userInput = inReader.readLine();
            if(userInput==null || "q".equals(userInput)){
                break;
            }
            session.write(userInput);
        }while (true);

        //关闭
        if (session != null) {
            if (session.isConnected()) {
                session.getCloseFuture().awaitUninterruptibly();
            }
            connector.dispose(true);
        }


    }
}
